package com.taobushi.aspect;

import com.taobushi.config.DS;
import com.taobushi.config.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
@Order(1)
public class DynamicDataSourceAspect {
    @Before("@annotation(dsi)")
    public void beforeSwitchDS(JoinPoint point,DS dsi){
        Object target = point.getTarget(); //?
        String[] parameterNames = ((MethodSignature) point.getSignature()).getParameterNames();
        System.out.println("parameterNames = " + Arrays.toString(parameterNames));

        String methodName = point.getSignature().getName();
        Class<?> aClass = point.getTarget().getClass();
        Class[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            Method method = aClass.getMethod(methodName, argClass);
            if (method.isAnnotationPresent(DS.class)){
                DS ds = method.getAnnotation(DS.class);
                dataSource = ds.value();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        DataSourceContextHolder.setDB(dataSource);
    }

    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point,DS DS){
        DataSourceContextHolder.clearDB();
    }
}
